﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;

using SBPweb.RIA.Shared.Contracts.Controllers;
using SBPweb.RIA.Shared.Contracts.Events;

using SBPweb.RIA.Client.Controls.Base;
using SBPweb.RIA.Client.Controls.Controllers;

namespace SBPweb.PlAzureNet.Client.Library.Controllers
{

    public class ModuleLoader
    {

        #region Consts

        private const string ModulesDirectory = "ClientBin/Modules/";

        #endregion

        #region Fields

        private IPackageLoaderController loader = RIA.Client.Controls.Controllers.PackageLoaderController.Controller;

        #endregion

        #region Constructor logic

        static ModuleLoader()
        {
            PackageLoaderController.RegisterApplicationSingleton();
        }

        public ModuleLoader()
        {
            Uri uri = new Uri(ExtendableApplication.Current.HostBaseUri.OriginalString + ModulesDirectory);

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ModulesDirectoryListingCompleted);
            wc.DownloadStringAsync(uri, uri.OriginalString);
        }

        #endregion

        #region Dependency properties

        public static DependencyProperty ControlPlacementProperty = DependencyProperty.Register("ControlPlacement", typeof(ControlPlacements), typeof(UserControl), null);
        public static DependencyProperty ControlPlacementArgumentProperty = DependencyProperty.Register("ControlPlacementArgument", typeof(string), typeof(UserControl), null);

        #endregion

        #region Event handlers

        private void ModulesDirectoryListingCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                var split = e.Result.Split(new string[] { ModulesDirectory }, StringSplitOptions.RemoveEmptyEntries).Where(x => x.Contains(".xap")).Select(x => x.Substring(0, x.IndexOf(".xap") + 4));

                foreach (string xapPath in split)
                {
                    loader.LoadFromPackage<UserControl>("/" + ModulesDirectory + xapPath, "Controls.MainControl", new AsyncRequestHandler<UserControl>(ControlLoaded));
                }
            }
        }

        private void ControlLoaded(object sender, EventArgs<UserControl> e)
        {
            IModulesRootPage root = ExtendableApplication.Current.RootVisual as IModulesRootPage;
            ControlPlacements cp = (ControlPlacements)e.Result.GetValue(ModuleLoader.ControlPlacementProperty);
            string cpa = e.Result.GetValue(ModuleLoader.ControlPlacementArgumentProperty) as string;
            root.PlaceModuleEntryControl(e.Result, cp, cpa);
        }

        #endregion

    }

}